/******************************************************************************
* Copyright (c) 2008-2010 Joel Becker. All Rights Reserved.
* http://tech.joelbecker.net
*
*    This is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License
*    version 3, as published by the Free Software Foundation.
*
*    This is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public
*    License along with this source file; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
******************************************************************************/
package trackingAlgorithms.videoprocessing;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

import javax.media.Format;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;

public class RgbDiffEffect extends RgbVideoEffect {

	
	private byte[] differ;
	public RgbDiffEffect(BackgroundUpdater bgUpdater) {
		supportedIns = new Format[] { new RGBFormat() };
		supportedOuts = new Format[] { new RGBFormat() };
		super.bgUpdater = bgUpdater;
	}
	
	public String getName() {
		return "RGB-Difference from Background Image";
	}

	public byte[] getDiffer() {
		return differ;
	}
	private void setDiff(byte[]a){
		differ = new byte[a.length];
		System.arraycopy(a, 0, differ, 0, a.length);
	}

	protected boolean processRGB(byte[] bin, byte[] bout, VideoFormat format) {
		
		
		if(backGroundImage != null) {	
			//// Calculate difference between input and background
			int now, before, diff;
			int k = 0;
			int j = 0;
		
			for(int i = 0; i < bin.length; i++) {
				now = inputImageArray[j][k];
				before = backGroundArray[j][k];
				diff = Math.abs(now - before);
				bout[i] = (byte)(diff);
//				RgbDiffEffect.coloredInputImage.set(k, j, diff);
				k++;
				if(k%format.getSize().width==0)
				{
					k = 0;
					j = (j+1)%format.getSize().height;
					
				}
			}
			
		} else {
			//// Make output show no differences
			for(int i = 0; i < bin.length; i++) {
				bout[i] = 0;
			}
		}
		setDiff(bout);
		return true;
	}
        public void setBackGround(BackgroundUpdater ba){
            bgUpdater = ba;
        }

        public static Image getImageFromArray(int[] pixels, int width, int height) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            WritableRaster raster = (WritableRaster) image.getData();
            raster.setPixels(0,0,width,height,pixels);
            return image;
        }
}



